import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Product, RemoteExcelConfig } from '../types'
import * as XLSX from 'xlsx'

export const useProductStore = defineStore('product', () => {
  const products = ref<Product[]>([])
  const remoteConfig = ref<RemoteExcelConfig | null>(null)
  const lastSyncTime = ref<string | null>(null)
  const syncInterval = ref<number | null>(null)

  // 添加产品
  const addProduct = async (product: Omit<Product, 'id'>) => {
    // 检查产品编码是否已存在
    if (products.value.some(p => p.productCode === product.productCode)) {
      throw new Error('产品编码已存在')
    }

    // 检查产品编码长度
    if (product.productCode.length < 3 || product.productCode.length > 20) {
      throw new Error('产品编码长度必须在3-20个字符之间')
    }

    // 添加新产品
    const newProduct: Product = {
      id: Date.now(),
      ...product
    }
    products.value.push(newProduct)
  }

  // 删除产品
  const deleteProduct = async (id: number) => {
    const index = products.value.findIndex(p => p.id === id)
    if (index > -1) {
      products.value.splice(index, 1)
    }
  }

  // 停止自动同步
  const stopAutoSync = () => {
    if (syncInterval.value) {
      window.clearInterval(syncInterval.value)
      syncInterval.value = null
    }
  }

  // 启动自动同步
  const startAutoSync = () => {
    // 先停止现有的同步定时器
    stopAutoSync()

    // 如果启用了自动同步，则设置新的定时器
    if (remoteConfig.value?.enabled) {
      // 每5分钟同步一次
      syncInterval.value = window.setInterval(async () => {
        try {
          await syncRemoteData()
        } catch (error) {
          console.error('自动同步失败:', error)
        }
      }, 5 * 60 * 1000) // 5分钟
    }
  }

  // 保存远程配置
  const saveRemoteConfig = async (config: RemoteExcelConfig) => {
    remoteConfig.value = config
    // 保存配置后，根据enabled状态启动或停止自动同步
    if (config.enabled) {
      startAutoSync()
    } else {
      stopAutoSync()
    }
  }

  // 同步远程数据
  const syncRemoteData = async () => {
    if (!remoteConfig.value?.url) {
      throw new Error('未配置远程Excel文件URL')
    }

    try {
      const response = await fetch(remoteConfig.value.url, {
        mode: 'cors',
        headers: {
          'Accept': 'application/json, application/octet-stream, text/plain, */*'
        }
      })
      if (!response.ok) {
        throw new Error(`无法访问远程文件: ${response.status} ${response.statusText}`)
      }

      const data = await response.arrayBuffer()
      const workbook = XLSX.read(data, { type: 'array' })

      // 使用配置的工作表名称或默认使用第一个工作表
      const sheetName = remoteConfig.value.sheetName || workbook.SheetNames[0]
      if (!sheetName) {
        throw new Error('未找到有效的工作表')
      }

      const worksheet = workbook.Sheets[sheetName]
      const rows = XLSX.utils.sheet_to_json(worksheet) as any[]

      // 清空现有产品
      products.value = []

      // 导入新数据
      for (const row of rows) {
        const productCode = row['产品编码']?.toString()
        const productName = row['产品名称']?.toString()
        const keyCode = row['关键代码']?.toString()

        if (productCode && productName && keyCode) {
          await addProduct({
            productCode,
            productName,
            keyCode
          })
        }
      }

      // 更新同步时间
      lastSyncTime.value = new Date().toISOString()
    } catch (error) {
      console.error('同步失败:', error)
      throw error
    }
  }

  return {
    products,
    remoteConfig,
    lastSyncTime,
    addProduct,
    deleteProduct,
    saveRemoteConfig,
    syncRemoteData,
    stopAutoSync
  }
}, {
  persist: true
}) 